package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.file.service.MinioService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private MinioService minioService;

    @Autowired
    private Configuration configuration;
    /**
     * 生成文章详情静态页面
     * 写入Minio
     * @param articleId
     * @param content
     */

    @Override
    public String buildContentHtml(Long articleId, String content) {
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map<String, Object> map = new HashMap();
            map.put("content", JSONArray.parseArray(content));
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String url = minioService.uploadHtmlFile("", articleId + ".html", is);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("minio 上传HTML失败");
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }

    @Autowired
    private ApArticleService apArticleService;

    @Override
    @Async
    public void saveHtmlUrl(Long articleId, String content) {
        String htmlUrl = buildContentHtml(articleId, content);
        ApArticle apArticle = new ApArticle();
        apArticle.setId(articleId);
        apArticle.setStaticUrl(htmlUrl);
        apArticleService.updateById(apArticle);
    }
}
